package com.imooc.controller;

import com.imooc.dataobject.ProductCategory;
import com.imooc.dataobject.ProductInfo;
import com.imooc.dto.OrderDto;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.form.ProductForm;
import com.imooc.service.CategoryService;
import com.imooc.service.ProductService;
import com.imooc.utils.KeyUtils;
import com.lly835.bestpay.rest.type.Get;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 功能描述: <br>
 * (卖家商品处理)
 *
 * @Author:Mr. xyb
 * @Date: 2018/5/18 17:33
 * @since: 1.8.0
 * @version: 1.0.0
 */
@Controller
@RequestMapping("/seller/product")
public class SellerProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;


    /**
     * 商品列表
     *
     * @param page 页码
     * @param size 每页数量
     * @param map  返回参数
     * @return
     */
    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "1") Integer size,
                             Map<String, Object> map) {
        /*创建参数对象*/
        PageRequest request = new PageRequest(page - 1, size);
        /*分页查询商品信息*/
        Page<ProductInfo> list = productService.findAll(request);
        map.put("productInfoPage", list);
        map.put("currentPage", page);
        map.put("size", size);
        // System.out.println(list.getContent());
        return new ModelAndView("product/list", map);
    }

    /**
     * 商品上架
     *
     * @param productId 商品id
     * @param map       返回参数
     * @return
     */
    @GetMapping("/on_sale")
    public ModelAndView onSale(@RequestParam("productId") String productId, Map<String, Object> map) {
        try {
            //上架
            productService.onSale(productId);
        } catch (SellException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/product/list");
            return new ModelAndView("common/error", map);
        }
        map.put("url", "/sell/seller/product/list");
        map.put("msg", ResultEnum.SUCCESS.getMessage());
        return new ModelAndView("common/success", map);
    }

    /**
     * 商品下架
     *
     * @param productId 商品id
     * @param map       返回参数
     * @return
     */
    @GetMapping("/off_sale")
    public ModelAndView offSale(@RequestParam("productId") String productId, Map<String, Object> map) {
        try {
            // 下架
            productService.offSale(productId);
        } catch (SellException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/product/list");
            return new ModelAndView("common/error", map);
        }
        map.put("url", "/sell/seller/product/list");
        map.put("msg", ResultEnum.SUCCESS.getMessage());
        return new ModelAndView("common/success", map);
    }

    /**
     * 进入商品添加/修改页面
     *
     * @param productId 商品id
     * @param map       返回参数
     * @return
     */
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "productId", required = false) String productId, Map<String, Object> map) {
        if (!StringUtils.isEmpty(productId)) {// 商品id不为空
            // 查询商品信息
            ProductInfo info = productService.findOne(productId);
            // 赋值
            map.put("productInfo", info);
        }
        /*查询所有类目*/
        List<ProductCategory> categoryList = categoryService.findAll();
        map.put("categoryList", categoryList);
        return new ModelAndView("product/index", map);
    }

    /**
     * 保存商品信息
     *
     * @param productForm   商品表单实体
     * @param bindingResult 处理实体的规范
     * @param map           返回参数
     * @return
     */
    @PostMapping("/save")
    @CacheEvict(cacheNames = "product", key = "123")// 保存之后将缓存层中的数据移除，防止前台系统脏读
    public ModelAndView save(@Valid ProductForm productForm, BindingResult bindingResult, Map<String, Object> map) {
        if (bindingResult.hasErrors()) {// 判断是否符合规范
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            map.put("url", "/sell/seller/product/index");
            return new ModelAndView("common/error", map);
        }
        ProductInfo productInfo = new ProductInfo();
        try {
            /*如果商品id不为空，则是修改商品信息*/
            if (!StringUtils.isEmpty(productForm.getProductId())) {
                productInfo = productService.findOne(productForm.getProductId());
            } else {// 新增商品信息
                productForm.setProductId(KeyUtils.getUniqueKey());
            }
            // 将商品表单数据复制到商品实体中
            BeanUtils.copyProperties(productForm, productInfo);
            productService.save(productInfo);// 保存
        } catch (SellException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/product/index");
            return new ModelAndView("common/error", map);
        }
        map.put("url", "/sell/seller/product/list");
        map.put("msg", ResultEnum.SUCCESS.getMessage());
        return new ModelAndView("common/success", map);
    }
}
